package kr.co.graviti.common.util;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.TreeSet;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.Calendar;
import java.util.Vector;
import java.util.regex.PatternSyntaxException;

import javax.servlet.http.HttpServletRequest;

public class CommonUtil {
	
	public static String getAddComma(String args)
    {
        args.trim();
        String symbol = "";
        String commavalue = "null";
        int r = 0;
        
        if(args.equals(""))
          return args;
        
        symbol = args.substring(0,1);
        
        StringTokenizer st = new StringTokenizer(args,".");
  
        while (st.hasMoreTokens()) {
               if(r == 0){
                       args = (String)st.nextToken();
               }else{
                       commavalue = (String)st.nextToken();
               }
               r++;
        }
  
        if(symbol.equals("-")) {//마이너스일때
            String va = "";
            if(args.length() <= 4)
                    if(r > 1){
                            return args + "." + commavalue;
                    }else{
                    return args;
            }
            va = args.substring(1);
            String value = "";
            int i = 1;
            int k = va.length();
            for(int j=va.length(); j > 0; j--) {
                    if(i%3 == 0 && i != 1 && i !=k ) {
                            value = ","+va.charAt(j-1)+value;
                    }else {
                            value = va.charAt(j-1)+value;
                    }
                    i++;
            }
    
            if(r > 1){
                return  (symbol.concat(value)) + "." + commavalue;
            }else{
                return  (symbol.concat(value));
            }
        }//마이너스일때
        else 
        {          
            if(args.length() <= 3)
            if(r > 1){
                    return args + "." + commavalue;
            }else{
                    return args;
            }
            
            String val = args;
            String value = "";
            int i = 1;
            int k = val.length();
            for(int j=val.length(); j > 0; j--) {
                    if(i%3 == 0 && i != 1 && i !=k ) {
                            value = ","+val.charAt(j-1)+value;
                    }else {
                            value = val.charAt(j-1)+value;
                    }
                    i++;
            }
            
            if(r > 1){
              return  value + "." + commavalue;
            }else{
              return  value;
            }       
        }
    }

    /**
    * Description : 콤마빼기
    * @param            String value : 금액(문자)
    * @return       String 
    */
    public static String removeComma(String value)
    {
        int flag = 0;
        String newVal = "";
        int index = 0;
        int temp = 0;
        flag = value.indexOf(44, 0);
        if(flag == -1)
            return value.trim();
        do
        {
            index = value.indexOf(44, temp);
            if(index == -1)
            {
                newVal = newVal.concat(value.substring(temp));
                break;
            }
            newVal = newVal.concat(value.substring(temp, index));
            temp = index + 1;
        } while(true);
        return newVal.trim();
    }

    
    /**
    * Description : 원하는 특수문자 삭제하기
    * @param            String value : 문자
    * @param            char remove_char : 특수문자
    * @return       String 
    */
    public static String removeChar(String value, char remove_char)
    {
        int flag = 0;
        String newVal = "";
        int index = 0;
        int temp = 0;
        flag = value.indexOf(remove_char, 0);
        if(flag == -1)
            return value.trim();
        do
        {
            index = value.indexOf(remove_char, temp);
            if(index == -1)
            {
                newVal = newVal.concat(value.substring(temp));
                break;
            }
            newVal = newVal.concat(value.substring(temp, index));
            temp = index + 1;
        } while(true);
        return newVal.trim();
    }
    
    /**
    * Description : null 체크
    * @param            String val : 문자
    * @return       String 
    */
    public static String nullCheck(String val)
    {
        if(val == null)
            return "";
        else
            return val;
    }
    
    /**
    * Description : 금액변환
    * @param            double source : 금액
    * @return       Double 
    */
    public static String koreaMoneyFormat(double source)
    {
        DecimalFormat df = (DecimalFormat)NumberFormat.getNumberInstance(Locale.KOREA);
        df.applyPattern("##,###,###,###,###");
        return df.format((new Double(source)).longValue());
    }

    
    /**
    * Description : 금액변환
    * @param            long source : 금액
    * @return       long 
    */
    public static String koreaMoneyFormat(long source)
    {
        DecimalFormat df = (DecimalFormat)NumberFormat.getNumberInstance(Locale.KOREA);
        df.applyPattern("##,###,###,###,###");
        return df.format(source);
    }
    
    /**
    * Description : 금액변환
    * @param            String source : 금액
    * @return       String 
    */
    public static String koreaMoneyFormat(String source)
    {
        if(source == null)
        {
            return "";
        } else
        {
            DecimalFormat df = (DecimalFormat)NumberFormat.getNumberInstance(Locale.KOREA);
            df.applyPattern("##,###,###,###,###");
            return df.format(Long.parseLong(source));
        }
    }
    
    /**
    * Description : 금액변환
    * @param            double source : 금액
    * @return       Double 
    */
    public static String koreaMoneyFormat2(String source)
    {
        if(source == null || source.equals("")){
                return "";
        } else {
                DecimalFormat df = (DecimalFormat)NumberFormat.getNumberInstance(Locale.KOREA);
                df.applyPattern("##,###,###,###,##0.00");
                return df.format((new Double(source)).doubleValue());
        }
    }
    
    /**
    * Description : byte 단위 자르기
    * @param            String str : 문자
    * @param            int startnum : 시작위치
    * @param            int endnum : 끝위치
    * @return       String 
    */
    public static String substring(String str, int startnum, int endnum)
    {
            int len = str.length();
            int nownum = 0;
            int checknum = endnum - startnum;
            String strstr = "";
            for(int i = 0; i < len ; i++)
            {
                    try
                    {
                            char[] b = str.substring(i,i+1).toCharArray();
                            
                            if((int)b[0] > 128 || (int)b[0] < 0)
                            {
                                    nownum = nownum + 2;
                            }
                            else
                            {
                                    nownum++;
                            }
                            strstr = strstr + str.substring(i,i+1);
                            if(nownum >= checknum)
                                    break;
                    }
                    catch(Exception e)
                    {
                            return str;
                    }
            }
            
            return strstr;
    }
    
    /**
    * Description : 날짜형태 2006/01/01 형태로 돌려줌
    * @param            String sDate : 날짜(문자)
    * @return       String 
    */
    public static String getDateFormat(String sDate) {
        if (sDate != null && sDate.length() == 8) {
                sDate = sDate.substring(0,4) + "/" + sDate.substring(4,6)+ "/" + sDate.substring(6,8);
        } else {
                sDate = "";
        }
        return sDate;
    }
    
    /**
     * Description : 오늘날짜구하기
     * @return       String YYYYMMDD
     */
     public static String getDate2() {
         Calendar calendar           = Calendar.getInstance();
         java.util.Date time         = calendar.getTime();
         SimpleDateFormat        simpleformat2   = new SimpleDateFormat("yyyyMMdd");
         String                  sformat2        = simpleformat2.format(time);
         return sformat2;
     }
    
    /**
    * Description : 날짜형태 2006-01-01 형태로 돌려줌
    * @param            String sDate : 날짜(문자)
    * @return       String 
    */
    public static String getDateFormatDesh(String sDate){
        if(sDate != null && sDate.length() == 8){
                sDate = sDate.substring(0,4) + "-" + sDate.substring(4,6)+ "-" + sDate.substring(6,8);
        } else{
                sDate = "";
        }
        return sDate;
    }
    
    /**
     * Description : 날짜형태 2006년 01월 01일 형태로 돌려줌
     * @param            String sDate : 날짜(문자)
     * @return       String 
     */
     public static String getDateKor(String sDate){
         if(sDate != null && sDate.length() == 8){
//                 sDate = sDate.substring(0,4) + "년 " + sDate.substring(4,6)+ "월 " + sDate.substring(6,8) + "일";
        	 sDate = sDate.substring(0,4) + "-" + sDate.substring(4,6)+ "-" + sDate.substring(6,8);
         } else{
                 sDate = "";
         }
         return sDate;
     }    
     
     /**
     * Description : 날짜형태 05월 14일 형태로 돌려줌 
     * @param sDate
     * @return
     */
    public static String getDateKorDay(String sDate){
    	if(sDate != null && sDate.length() == 8){
//            sDate = sDate.substring(4,6)+ "월 " + sDate.substring(6,8) + "일";
            sDate = sDate.substring(4,6)+ "-" + sDate.substring(6,8);
	    } else{
	            sDate = "";
	    }
    	 return sDate;
     }
     
    /**
     * Description : 날짜형태(YYYYMMDD)형태의 String을 특정날자의 요일을 알려준다.
     * @param sDate
     * @return
     */
    public static String getYoil(String sDate){
    	if(sDate != null && sDate.length() == 8){
//    		String[] dayOfWeek={"일","월","화","수","목","금","토"};
    		String[] dayOfWeek={"sun","mon","tue","wed","thu","fri","sat"};
    		Calendar cal=new GregorianCalendar();
    		cal.set(Calendar.YEAR, Integer.parseInt(sDate.substring(0,4)));
    		cal.set(Calendar.MONTH, Integer.parseInt(sDate.substring(4,6))-1 );
    		cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(sDate.substring(6,8)));
    		
    		sDate=dayOfWeek[cal.get(Calendar.DAY_OF_WEEK)-1];

    	}else{
    		sDate = "";
    	}
    	return sDate;
    }
     
    /**
    * Description : 날짜형태 2006-01-01 09:00 형태로 돌려줌
    * @return       String YYYY-MM-DD HH:MM
    */    
    public static String getDateTimeFormatDesh(String sDate){
        // YYYY-MM-DD hh:mm 형태
        if(sDate != null && sDate.length() == 12){
                sDate = sDate.substring(0,4) + "-" + sDate.substring(4,6)+ "-" + sDate.substring(6,8) + " " +  sDate.substring(8,10) + ":" + sDate.substring(10);
        // YYYY-MM-DD hh:mm:ss 형태
        } else if(sDate != null && sDate.length() == 14){
                sDate = sDate.substring(0,4) + "-" + sDate.substring(4,6)+ "-" + sDate.substring(6,8) + " " +  sDate.substring(8,10) + ":" + sDate.substring(10,12) + ":" + sDate.substring(12);
        } else {
                sDate = "";
        }
        return sDate;
    }

    /**
    * Description : 날짜형태 2006.01.01 09:00 형태로 돌려줌
    * @param            String sDate  : 날짜(문자)
    * @param        String sGubun : 1) YYYY.MM.DD  
    *                               2) YYYY.MM.DD HH:YY
    *                               3) YYYY.MM.DD HH:YY:SS
    * @return       String YYYY.MM.DD hh:mm:ss
    */
    public static String getDateTimeFormat(String sDate, String sGubun)
    {
            if(sGubun == null){
                    sDate = "";
            } else if(sGubun.equals("1")){
            
                    if(sDate != null && sDate.length() > 7){
                            sDate = sDate.substring(0,4) + "." + sDate.substring(4,6)+ "." + sDate.substring(6,8);
                    } else {
                            sDate = "";
                    }
            } else if(sGubun.equals("2")){
                    if(sDate != null && sDate.length() > 10){
                            sDate = sDate.substring(0,4) + "." + sDate.substring(4,6)+ "." + sDate.substring(6,8) + " " +  sDate.substring(8,10) + ":" + sDate.substring(10,12);
                    } else {
                            sDate = "";
                    }                       
                    
            } else if(sGubun.equals("3")){
                    if(sDate != null && sDate.length() == 14){
                            sDate = sDate.substring(0,4) + "." + sDate.substring(4,6)+ "." + sDate.substring(6,8) + " " +  sDate.substring(8,10) + ":" + sDate.substring(10,12)+ ":" + sDate.substring(1214);                       
                    } else {
                            sDate = "";
                    }                       
            }
            return sDate;
    }

    /**
    * Description : 오늘날짜구하기
    * @return       String YYYYMMDD
    */
    public static String getDate() {
        Calendar calendar           = Calendar.getInstance();
        java.util.Date time         = calendar.getTime();
        SimpleDateFormat        simpleformat2   = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
        String                  sformat2        = simpleformat2.format(time);
        return sformat2;
    }
      
    /**
    * Description : 이전날짜구하기
    * @return       String YYYYMMDD
    */            
    // 원하는날짜에 원하는 일자만큼 더해서 구해오기.
    
    public static String addDate(String sDate, int today) {
            String returnDate = "";
            if(sDate != null){
                Calendar cal    = Calendar.getInstance();
                int year    = Integer.parseInt(sDate.substring(0,4));
                int mon   = Integer.parseInt(sDate.substring(4,6)) -1;
                int day     = Integer.parseInt(sDate.substring(6,8));
                cal.set(year, mon, day);
                    cal.add(cal.DATE,today);
                    year = cal.get(cal.YEAR); 
                    mon = cal.get(cal.MONTH) + 1; 
                    day = cal.get(cal.DATE); 
                    String str = "";
                    str += year;
                    if(mon < 10) str += "0";
                    str += mon;
                    if(day < 10) str += "0";
                    str += day;
                    returnDate = str;
            } else {
                    returnDate = "";        
            }
            return  returnDate;
    }

    /**
    * Description : 오늘날짜 및 시간 구하기
    * @return       String YYYYMMDDHHMM
    */
    public static String getDateYYYYMMDDHHMM() {
        Calendar calendar    = Calendar.getInstance();
        java.util.Date time = calendar.getTime();

        SimpleDateFormat        simpleformat2   = new SimpleDateFormat("yyyyMMddHHmm", Locale.US);
        String                  sformat2        = simpleformat2.format(time);

        return sformat2;
      }
           
     /**
      * Description : 오늘날짜구하기 '- '
      * @return       String 2006년 1월 1일
      */       
     public static String getDateDesh() {
        Calendar calendar    = Calendar.getInstance();
        java.util.Date time = calendar.getTime();

        SimpleDateFormat        simpleformat2   = new SimpleDateFormat("yyyyMMdd", Locale.US);
        String                  sformat2        = simpleformat2.format(time);
            String sformat2_YY = "";
            String sformat2_MM = "";
            String sformat2_DD = "";
            
            sformat2_YY = sformat2.substring(0,4);
            sformat2_MM = sformat2.substring(4,6);
            sformat2_DD = sformat2.substring(6,8);
            
            //sformat2 = sformat2_YY + "-" + String.valueOf(Long.parseLong(sformat2_MM))+"-" + String.valueOf(Long.parseLong(sformat2_DD));
            sformat2 = sformat2_YY + "-" + sformat2_MM+"-" + sformat2_DD;

        return sformat2;
      }
     
    /** 
    * 기능 : 구분자에 따라 문자열 분리    <br>
    *@param     str        분리할 문자열
    *@param     _char      구분자
    *@return                       분리된 문자열 배열
    */
    public static String[] getTokenizer(String str, char _char)
    {
            String tempbuf = str;
            
            if (str == null) return null;
            if (str.length() == 0) return null;
            
            int j=0;
            for(int i=0;i<str.length();i++)
            {
                    if(tempbuf.charAt(i) == _char)  
                    {
                            j++;
                    }       
            }

            String rtnbuf[] = new String[j];
    
            int li_start = 0;
            int li_end   = 0;
            int idx =0;
            for( int li_idx = 0; li_idx < rtnbuf.length + 1; li_idx++){
                li_end = str.indexOf(_char,  li_start);
            if(li_end == 0){
                    
            } else if(li_end != -1){
                    rtnbuf[idx] = str.substring(li_start, li_end );
                    idx++;
                } else {
                    rtnbuf[idx] = str.substring(li_start );
                    idx++;
                }
                li_start = li_end + 1;
            }
            return rtnbuf;
    }
    
    /** 
      * 기능 : 구분자에 따라 문자열 분리    <br>
      *@param     str        분리할 문자열
      *@param     klm        문자열
      *@return                       분리된 문자열 배열
      */
    public static String[] split(String str, String dlm)
    {
            int max_num = 0, prepos = 0, pos = 0, i = 0;
            
            if (!str.equals("")) {
                    pos = str.indexOf(dlm, prepos);
                    while (pos >= 0) {
                            max_num = max_num + 1;
                            
                            prepos = pos + dlm.length();
                            pos = str.indexOf(dlm, prepos);
                    }
                    max_num = max_num + 1;
                    
                    String[] str_array = new String[max_num];
                    prepos = 0;
                    pos = str.indexOf(dlm, prepos);
                    while (pos >= 0)
                    {
                            str_array[i] = str.substring(prepos, pos);
                            prepos = pos + dlm.length();
                            pos = str.indexOf(dlm, prepos);
                            i = i + 1;
                    }
                    str_array[i] = str.substring(prepos, str.length());
                    
                    return str_array;
                    
            } else {
                    return null;
            }
    }
    
    /** 
     * 기능 : 구분자에 따라 문자열 분리    <br>
     *@param     str        분리할 문자열
     *@param     klm        문자열
     *@return                       분리된 문자열 배열
     */
   public static ArrayList splitArrayList(String str, String dlm)
   {
           int max_num = 0, prepos = 0, pos = 0, i = 0;
           List returnValue = new ArrayList();
           
           if (!str.equals("")) {
                   pos = str.indexOf(dlm, prepos);
                   while (pos >= 0) {
                           max_num = max_num + 1;
                           
                           prepos = pos + dlm.length();
                           pos = str.indexOf(dlm, prepos);
                   }
                   max_num = max_num + 1;
                   
                   String[] str_array = new String[max_num];
                   prepos = 0;
                   pos = str.indexOf(dlm, prepos);
                   while (pos >= 0)
                   {
                           str_array[i] = str.substring(prepos, pos);
                           prepos = pos + dlm.length();
                           pos = str.indexOf(dlm, prepos);
                           i = i + 1;
                   }
                   str_array[i] = str.substring(prepos, str.length());
                   
                   for (int k = 0; k < str_array.length; k ++) {
                	   returnValue.add(k, str_array[k]);
                   }
                   
                   return (ArrayList) returnValue;
                   
           } else {
                   return null;
           }
   }    
    
    /** 
        * 기능 : 마지막 일 구하기    <br>
        *@param     String     년월
        *@return               마지막일자 포함 yyyymmdd
        */
     public static String getLastDay(String argyyyymm)
     {
            int LastDay = 0;
            int year = 0;
            int month = 0;
            String returnDay = "";
            
            if(argyyyymm != null && argyyyymm.length() == 6){
                    year = Integer.parseInt(argyyyymm.substring(0, 4));
                    month = Integer.parseInt(argyyyymm.substring(4, 6));
            
                    switch (month) {
                              case 2: {
                                            if ( ( (year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0))
                                                      LastDay = 29;
                                            else
                                                      LastDay = 28;
                                            break;
                              }
                              case 4:
                                            LastDay = 30;
                                            break;
                              case 6:
                                            LastDay = 30;
                                            break;
                              case 9:
                                            LastDay = 30;
                                            break;
                              case 11:
                                            LastDay = 30;
                                            break;
                              default:
                                            LastDay = 31;
                                            break;
                    }
                    
            } else {
                    returnDay = argyyyymm + String.valueOf(LastDay);
            }
            return returnDay;
     }
          
     public static String convertKor(String str) throws Exception {
         String rtnStr = "";
         
         if (str != null || !str.equals("")) {
             rtnStr = new String(str.getBytes("8859_1"),"euc-kr");
         }         
         return rtnStr;
     }
     
     public static String convertUTF8(String str) throws Exception {
         String rtnStr = "";
         
         if (str != null || !str.equals("")) {
             rtnStr = new String(str.getBytes("8859_1"),"utf-8");
         }         
         return rtnStr;
     }

    public static String toKsc(String str) throws UnsupportedEncodingException, NullPointerException {  //한글처리를 위한 부분
        return new String(str.getBytes("8859_1"),"euc-kr");
    	//return str;
    }
    public static String toEng(String str) throws UnsupportedEncodingException, NullPointerException {  //한글처리를 위한 부분
        return new String(str.getBytes("KSC5601"),"8859_1");
    }

    
    /**
    * 긴글 텍스트
    */
    public static String cutBytes(String strSource, int cutByte) {
        return cutBytes( strSource, cutByte, true, "..." );
    }

    public static String cutBytes(String strSource, int cutByte, boolean bTrim) {
        return cutBytes( strSource, cutByte, bTrim, "..." );
    }

    public static String cutBytes(String strSource, int cutByte, boolean bTrim, String strPostfix){

        if( strSource == null ) return "";

        strPostfix = (strPostfix == null) ? "..." : strPostfix;
        int postfixSize = 0;
        for( int i=0; i < strPostfix.length(); i ++ ) {
            if( strPostfix.charAt( i ) < 256 )
                postfixSize += 1;
            else 
                postfixSize += 2;
        }

        if( postfixSize > cutByte )
            return strSource;

        if( bTrim ) strSource = strSource.trim(); 
        char[] charArray = strSource.toCharArray();

        int strIndex = 0;
        int byteLength = 0;
        for( ; strIndex < strSource.length(); strIndex++ ) {
            int byteSize = 0;
            if( charArray[ strIndex ] < 256) {
                // 1byte character 이면
                byteSize = 1; 
            } else {
                // 2byte character 이면
                byteSize = 2;
            }

            if( ( byteLength + byteSize ) > cutByte - postfixSize )	break;

            byteLength = byteLength += byteSize;
        }        

        if( strIndex == strSource.length() ) 
            strPostfix = "";
        else {
            if( (byteLength + postfixSize) < cutByte )
                strPostfix = " " + strPostfix;
        }
        return strSource.substring( 0, strIndex ) + strPostfix;        
    }
    
    public String getOnlyFileName(String nameWithPath) {
        String[] parts = nameWithPath.split("\\\\");
         return parts[parts.length - 1];
    }

    public static String strNullChk(String str) {	//null 체크를위한 부분
        if( str == null || str.equals("") )	str="";
        str = filterXss(str);
        return str;
    }

    
    /**
     * String 공백제거
     * @param str
     * @return
     */
    public static String strRemoveGap(String str) {
    	
    	str = str.replaceAll(" ", "");
    	
    	return str;
    }
    
    public static String filterXss(String str) {
    	String avatag = "p,br,font";
    	
    	str = str.replaceAll("<", "&lt;");
    	str = str.replaceAll("\0", " ");
    	if (!avatag.equals("")) {
    		avatag.replaceAll(" ", "");
    		String [] st = avatag.split(",");
    		
    		for (int i = 0; i < st.length; i ++) {
    			str = str.replaceAll("&lt;" + str + " ", "<" + str + " ");
    			str = str.replaceAll("&lt;" + str + ">", "<" + str + ">");
    			str = str.replaceAll("&lt;/" + str, "</" + str);
    		}
    	}
    	
    	return str;
    }
    
    public static String html(Object str) {
    	String s = "";
    	
    	if (str == null) {
    		return s;
    	} else {
    		s = String.valueOf(str);
    		s = s.replaceAll("&", "&amp");
    		s = s.replaceAll("\'", "&#039");
    		s = s.replaceAll("\"", "&#34;");
    		s = s.replaceAll("<", "&lt;");
    		s = s.replaceAll(">", "&gt;");
    	}
    	
    	return s;
    }
    
    public static String getReplaceMetaTag(String str) {

    	try {
	    	str = str.replaceAll("\\*", "\\\\*");
	    	str = str.replaceAll("\\?", "\\\\?");
	    	str = str.replaceAll("\\+", "\\\\+");
	    	str = str.replaceAll("\\[", "\\\\[");
	    	str = str.replaceAll("\\{", "\\\\{");
	    	str = str.replaceAll("\\(", "\\\\(");
	    	str = str.replaceAll("\\)", "\\\\)");
	    	str = str.replaceAll("\\^", "\\\\^");
	    	str = str.replaceAll("\\$", "\\\\\\$");
    	} catch (PatternSyntaxException e) {
    		throw new InternalError("Invalid pattern : " + e.getMessage());
    	}
    	return str;
    }
    
    public static String getRepBackSlash(String str) {
    	if( str == null )	str="";
    	str = str.replaceAll("\\\\", "");
    	return str;
    }
    
    
    /**
	 * map 안에 있는 object -> String
	 * @param map
	 * @param key
	 * @param defaultValue
	 * @return
	 */
    public static String conMapToString(Map map , String key, String defaultValue){
        try{
            if(map == null) return defaultValue;
            if(map.get(key) != null) return map.get(key).toString();
        }catch(Exception e){
            System.out.println("String 으로 변환할 수 없는 Object 입니다.");
        }
        return defaultValue;
    }
    
    public static String strNullChk(String str, String p) {	//null 체크를위한 부분
        if( str == null || str.equals("") )	str=p;
        return str;
    }
    
    public static String intNullChk(String str) {	//null 체크를위한 부분
        if( str == null || str.equals("") )	str="0";
        return str;
    }
    
    /**
    * 오늘날짜초까지 리턴 
    */
    public static String getCurDateSec() { 
//        String pattern = "yyyy년MM월dd일 hh시mm분ss초";
    	String pattern = "yyyy-MM-dd hh:mm:ss";
        SimpleDateFormat dateFormatter = new SimpleDateFormat(pattern, new Locale("ko", "KOREA")); 
        String curDate = dateFormatter.format(new java.util.Date()); 
        return curDate; 
    }
    
    /**
     * 오늘날짜초까지 리턴 한글 없음
     */
     public static String getCurDateSec2() {
         SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyyMMddhhmmss"); 
         String curDate = dateFormatter.format(new java.util.Date()); 
         return curDate; 
     }

    /**
    * 오늘날짜 리턴 
    */
    public static String getCurDate() { 
        SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyyMMdd"); 
        String curDate = dateFormatter.format(new java.util.Date()); 
        return curDate; 
    } 

    /**
    * 현재년도 리턴
    */
    public static String getCurYear() { 
        SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy"); 
        String curYear = dateFormatter.format(new java.util.Date()); 
        return curYear; 
    }

    /**
    * 현재월 리턴
    */
    public static String getCurMon() { 
        SimpleDateFormat dateFormatter = new SimpleDateFormat("MM"); 
        String curMon = dateFormatter.format(new java.util.Date()); 
        return curMon; 
    }

    /**
    * 현재월 리턴
    */
    public static String getCurDay() { 
            SimpleDateFormat dateFormatter = new SimpleDateFormat("dd"); 
            String curDay = dateFormatter.format(new java.util.Date()); 
            return curDay; 
    }

    /**
    * 현재시간 리턴
    */
    public static String getCurHour() { 
        SimpleDateFormat dateFormatter = new SimpleDateFormat("HH"); 
        String curHour = dateFormatter.format(new java.util.Date()); 
        return curHour; 
    }
    
    /**
    * @param size   전체길이
    * @param value  현재 맥스값
    * @return       재정의된 현재 맥스값
    */
    public static String getStrFormat(int size, String value) {
        String rtnVal = "";        
        for(int i = 0; i < size - value.length() + 1; i ++) {
            if(i < size - value.length()) {
                rtnVal += "0";
            } else {
                rtnVal += value.toString();
                break;
            }
        }
        return rtnVal;
    }
    
    /*
     *  자바스크립트 연동관련 
     */
    public static String printAlert(String str) {
        StringBuffer sb = new StringBuffer();
        
        sb.append("<script>");
        sb.append("alert(\"").append(str).append("\");");
        sb.append("</script>");
        
        return sb.toString();
    }
    
	public static String printAlertReturn(String str){
    	String str1 = "";
        
        str1 = "<script>";
        str1 += "alert(\"" + str + "\");";
        str1 += " return;";
        str1 += "</script>";
        return str1;
    }

    public static String printAlertBack(String str) {
        String str1 = "";

        str1 = "<script>";
        str1 += "alert(\"" + str + "\");";
        str1 += "history.go(-1);";
        str1 += "</script>";
        return str1;
    }
    
    public static String printAlertClose(String str) {
        String str1 = "";
        
        str1 = "<script>";
        str1 += "alert(\"" + str + "\");";
        str1 += "self.close();";
        str1 += "</script>";
        return str1;    	
    }
    
    public static String printAlertGo(String str, String url) {
        String str1 = "";
        
        str1 = "<script>";
        str1 += "alert(\"" + str + "\");";
        str1 += "location.href = \"" + url + "\";";
        str1 += "</script>";
        return str1;
    }
    
    public static String printAlterGoParent(String msg, String url) {
        String str1 = "";
        
        str1 = "<script>";
        str1 += "alert(\"" + msg + "\");";
        str1 += "parent.location.href=\"" + url + "\";";
        str1 += "</script>";
        return str1;
    }
    
    public static String printNomsgGoParent(String url) {
        String str1 = "";
        
        str1 = "<script>";
        str1 += "parent.location.href=\"" + url + "\";";
        str1 += "</script>";
        return str1;
    }
    
    public static String printMsgGoParent(String msg, String url) {
    	StringBuffer sb = new StringBuffer();
    	
    	sb.append("<script>");
    	sb.append("alert(\"").append(msg).append("\");");
    	sb.append("parent.location.href=\"").append(url).append("\";");
    	sb.append("</script>");
    	
    	return sb.toString();
    }
    
    public static String printGo(String url) {
        String str1 = "";
        
        str1 = "<script>";
        str1 += "location.href = \"" + url + "\";";
        str1 += "</script>";
        return str1;
    }
    
    public static String printNomsgCloseReload() {
        String str1 = "";
        
        str1 = "<script>";  
        str1 += "opener.document.location.reload();";
        str1 += "self.close();";
        str1 += "</script>";
        return str1;
    }    
    
    public static String printAlertCloseReload(String str) {
        String str1 = "";
        
        str1 = "<script>";
        str1 += "alert(\"" + str + "\");";        
        str1 += "opener.document.location.reload();";
        str1 += "self.close();";
        str1 += "</script>";
        return str1;
    }
    
    
    /**
     * Jsp request객체 -> java HashMap으로 변환
     * @throws java.lang.Exception
     * @return map
     * @param req
     */
    public static HashMap getRequest(HttpServletRequest req) throws Exception {
        HashMap map = new HashMap();
        Enumeration _enum = req.getParameterNames();
        
        while (_enum.hasMoreElements()) {
            String key = (String) _enum.nextElement();
            String[] value = req.getParameterValues(key);
            
            if (value.length == 1) {
              map.put(key, req.getParameter(key));
            } else if (value.length > 1) {
                Vector v = new Vector();
                
                for (int i = 0; i < value.length; i++) {
                    v.add(v.size(), value[i]);
                }
                map.put(key, v);
            }
        }
        return map;
    }
    
    /**
     * 지정된 범위안에서의 난수발
     * @param n1	최대값
     * @param n2	최소값
     * @return		난수 
     */
	public static int randomRange(int n1, int n2) {
    	return (int) (Math.random() * (n2 - n1 + 1)) + n1;
  	}
	
	public static String[] removeDupValueArray(String [] strArr) {
		
		TreeSet<String> tSet = new TreeSet<String>();
		
		for (int i = 0; i < strArr.length; i ++) {
			tSet.add(strArr[i]);
		}
		
		Iterator<String> it = tSet.iterator();
		String [] removedDupArray = new String[tSet.size()];
		int i = 0;
		while (it.hasNext()) {
			removedDupArray[i] = it.next();
			i ++;		
		}
		
		return removedDupArray;
	}
	
	public static String removeTag(String str) {
		String _str = "";
		_str = str.replaceAll("<(/)?([a-zA-Z]*)(\\s[a-zA-Z]*=[^>]*)?(\\s)*(/)?>", "");
		_str = _str.replaceAll("&nbsp;", "");
		_str = _str.replaceAll("&quot;", "'");
		_str = _str.replaceAll("&lsquo;", "'");
		_str = _str.replaceAll("&rsquo;", "'");
		return _str;
	}
	
	public static String optimizeXMLString(String str) {
		String [] arrStrList = {"\r\n", "\t", "%26", "<", "\"\"", "&"};
		String [] arrReplaceList = {"\n","","&", "&lt;", "\"", "&amp;"};
		
		for (int i = 0; i < arrStrList.length; i ++) {
			str = str.replaceAll(arrStrList[i], arrReplaceList[i]);
		}
		
		return str;
	}
	
    public static String nl2br(String comment) {
        int length = comment.length();
        StringBuffer buffer = new StringBuffer();

        for (int i = 0; i < length; ++i)
        {
            String comp = comment.substring(i, i+1);
            if ("\r".compareTo(comp) == 0)
            {
                comp = comment.substring(++i, i+1);
                if ("\n".compareTo(comp) == 0)
                    buffer.append("<BR>\r");
                else
                    buffer.append("\r");
            }

            buffer.append(comp);
        }
        return buffer.toString();
    }	
    
	public static String optimizeTextString(String str) {
		String [] arrStrList 		= {"\""};
		String [] arrReplaceList 	= {"&quot;"};
		
		for (int i = 0; i < arrStrList.length; i ++) {
			str = str.replaceAll(arrStrList[i], arrReplaceList[i]);
		}
		
		return str;
	}   
	
	public static String renameFilename(String prefix, String uploadDir, String orgFileName) {
		
		String changeFilename = "";
		String orgExt = "";
		
		orgExt = orgFileName.split("\\.")[orgFileName.split("\\.").length-1];
		File orgf = new File(new StringBuffer(uploadDir).append("/").append(orgFileName).toString());
		changeFilename = new StringBuffer(prefix).append("_").append(getCurDateSec2()).append("_").append(randomRange(100, 900)).toString();
		changeFilename = new StringBuffer(changeFilename).append(".").append(orgExt).toString();
		orgf.renameTo(new File(new StringBuffer(uploadDir).append("/").append(changeFilename).toString()));	
		
		return changeFilename;
	}	
	
	/** 확장자 검사 
	 * @param str
	 * @return
	 */
	public static String fileext(String str){
		String ext = "";
		if(!str.equals("")){
			int dot = str.lastIndexOf(".");
			ext	= str.substring(dot+1);
		}
		return ext;
	}
	
	public static boolean isNull(Object o) {
		return (o == null) ? true : false;
	}
	
	public static boolean contains(String s, String in) {
		if (isNull(s))
			return false;
		return s.indexOf(in) > -1 ? true : false;
	}
	
	public static boolean contains(String s, String [] in) {
		boolean flag = false;
		if (isNull(in))
			return false;
	
		for (int i = 0; i < in.length; i ++) {
			if (equals(s, in[i])) {
				flag = true;
				break;
			}
		}
		return flag;
	}
	
	public static boolean equals(String s, String s1) {
		if (s == null && s1 == null)
			return true;
		if (s == null || s1 == null)
			return false;
		else
			return s.equalsIgnoreCase(s1);
	}
	
	public static String getLast(String s, String delim) {
		if (isNull(s))
			return "null";
		if (!contains(s, delim))
			return s;
		StringTokenizer st = new StringTokenizer(s, delim);
		String last = null;
		while (st.hasMoreElements()) {
			last = st.nextToken();
		}
		return last;
	}
	
	public static String toLowerCase(String s) {
		if (isNull(s))
			return s;
		return s.toLowerCase();
	}
	
	public static String[] divideStringArray(String str, String delim) {
		if (str == null) return null;
		String [] result = null;
		StringTokenizer st = new StringTokenizer(str, delim);
		result = new String[st.countTokens()];
		for (int i = 0; st.hasMoreElements(); i ++)
			result[i] = st.nextToken();
		
		return result;
	}
	
	public static String getFileTypeCd(String contentType) {
		
		String [] temp = contentType.split("\\/");
		String cd = "";
		if (temp.length > 0) {
			if (temp[1].equals("jpg") || temp[1].equals("gif") || temp[1].equals("jpeg") || temp[1].equals("png")) {
				cd = "1";
			} else if (temp[1].equals("pdf")) {
				cd = "3";
			} else if (temp[1].equals("x-ms-wmv")) {
				cd = "5";
			}
		} else {
			String kind = "6";
		}
		
//		Select Case lcase(FileType)
//	     Case "asf"
//	           GetContentType = "video/x-ms-asf"
//	     Case "avi"
//	           GetContentType = "video/x-msvideo"
//		 Case "mid"
//	           GetContentType = "audio/midi"
//		 Case "midi"
//	           GetContentType = "audio/x-midi"
//		 Case "bmp"
//	           GetContentType = "image/bmp"
//		 Case "png"
//	           GetContentType = "image/png"
//	     Case "gif"
//	           GetContentType = "image/gif"
//	     Case "jpg"
//	           GetContentType = "image/jpeg"
//	     Case "jpeg"
//	           GetContentType = "image/jpeg"
//	     Case "ram"
//	           GetContentType = "video/vnd.rn-realvideo"
//	     Case "rm"
//	           GetContentType = "video/vnd.rn-realvideo"
//	     Case "rmvb"
//	           GetContentType = "video/vnd.rn-realvideo"
//	     Case "rpm"
//	           GetContentType = "audio/x-pn-realaudio-plugin"
//	     Case "ra"
//	           GetContentType = "video/vnd.rn-realvideo"
//	     Case "wav"
//	           GetContentType = "audio/wav"
//	     Case "wmv"
//	           GetContentType = "video/x-ms-wmv"
//	     Case "wma"
//	           GetContentType = "audio/x-ms-wma"
//	     Case "mp3"
//	           GetContentType = "audio/mpeg3"
//	     Case "mpg"
//	           GetContentType = "video/mpeg"
//	     Case "mpeg"
//	           GetContentType = "video/mpeg"
//	     Case "flv"
//	           GetContentType = "video/x-flv"
//	     Case "swf"
//	           GetContentType = "application/x-shockwave-flash"
//	     Case Else
//	           GetContentType = "application/ms-download"		
		
		return cd;
	}
	
	public static String getSayoeYisaSplitChar() {
		return CommonVariable.SAHOEYISA_SPLIT_CHAR;
	}
}
